//
//  KLWebSocket.m
//  WebRTCDemo_iOS
//
//  Created by szblsx2 on 2020/3/5.
//  Copyright © 2020 szblsx2. All rights reserved.
//

#import "KLWebSocket.h"
#import "SRWebSocket.h"

@interface KLWebSocket ()<SRWebSocketDelegate>
// socket对象
@property (nonatomic, strong) SRWebSocket *mWebSocketClient;

@end

@implementation KLWebSocket

/**连接socket*/
- (void)connectWebSocketWithUrlString:(NSString *)urlString
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    _mWebSocketClient = [[SRWebSocket alloc] initWithURLRequest:request];
    _mWebSocketClient.delegate = self;
    [_mWebSocketClient open];
}

/**断开连接*/
- (void)closeWebSocket
{
    if (_mWebSocketClient && (_mWebSocketClient.readyState == SR_OPEN || _mWebSocketClient.readyState == SR_CONNECTING)) {
        [_mWebSocketClient close];
        _mWebSocketClient = nil;
        if (self.socketConnect) {
            self.socketConnect(NO);
        }
    }
}

/**向服务器发送信令*/
- (void)sendData:(NSString *)jsonData
{
    if (_mWebSocketClient && _mWebSocketClient.readyState == SR_OPEN) {
        [_mWebSocketClient send:jsonData];
    }
}

#pragma mark - SRWebSocketDelegate

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message
{
    if (self.onDataRecvice) {
        self.onDataRecvice(message);
    }
}

- (void)webSocketDidOpen:(SRWebSocket *)webSocket
{
    NSLog(@"");
    if (self.socketConnect) {
        self.socketConnect(YES);
    }
}

- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error
{
    NSLog(@"");
    if (self.socketConnect) {
        self.socketConnect(NO);
    }
}

- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean
{
    NSLog(@"");
    if (self.socketConnect) {
        self.socketConnect(NO);
    }
}

- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload
{
    NSLog(@"");
}


@end
